import React, { useState } from 'react';
import { Modal, Form, Row, Col, Input, Upload, message, Button } from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import { UploadOutlined } from '@ant-design/icons';
import ASelect, { ASelectOptionType } from '@/components/SelfComp/ASelect';
import { AppItem } from '@/types/app';
import { FormModalProps, DataItem } from '@/types/global';
import { ImportTradeRecord } from '@/types/trade';
import { formLayout, modalFormItemLayout } from '@/utils/commons';

type AddTradeProps<T> = FormModalProps<T> & {
  appList: AppItem[];
  systemData: DataItem[];
  clusterData: DataItem[];
  downloadTemplateFile: (fileName: string) => void;
}

type AddTradePropsEx<T> = Omit<AddTradeProps<T>, 'formData'>;

type ImportTradeFormValue = ImportTradeRecord

const FormItem = Form.Item;

const templateTypeOptions: DataItem[] = [
  { key: '1', value: '普通模板' },
  { key: '3', value: 'AFA3模板' },
  { key: '4', value: 'AFA4模板' },
  { key: '5', value: 'AFA5模板' },
]

/**
 * 批量导入交易
 * <p>根据excel模板填写数据，然后上传excel，实现批量导入</p>
 * 
 * @param props 
 * @returns 
 */
const ImportTradeModal: React.FC<AddTradePropsEx<ImportTradeFormValue>>  = (props) => {
  // AFA模板对应的栏位是否可见
  const [afaVisible, setAfaVisible] = useState<boolean>(false);
  // 上传的文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [appData, setAppData] = useState<DataItem[]>([]);
  const [systemCode, setSystemCode] = useState<string>('');
  const [templateName, setTemplateName] = useState<string>('普通模板');
  const [form] = Form.useForm<ImportTradeFormValue>();

  const onOk = () => {
    form.validateFields().then(fieldsValue => {
      console.info(fieldsValue);
      const values = {
        ...fieldsValue
      };
      console.log('Received values of form: ', values);
      console.log(fileList);
      if (fileList.length < 1) {
        message.warn('请先选择一个文件');
        return;
      }
      if (fileList.length > 1) {
        message.warn('一次只能上传一个文件');
        return;
      }
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        const formData = new FormData();
        formData.append('data', JSON.stringify(values));
        formData.append('file', fileList[0] as RcFile);
        onHandlerOK(formData);
      }
    }).catch();
  };

  const onCancel = () => {
    // 先清除form表单
    form.resetFields();
    const { onHandlerCancel } = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 交易所属系统栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const templateTypeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // console.log('templateTypeChange', value);
    if (value === '1') {
      // 普通模板
      setAfaVisible(false);
      setTemplateName('普通模板');
      // 不展示系统，集群，应用的栏位
    } else {
      message.info('存量交易可通过对应的 AFA3/4/5 IDE 导出');
      setAfaVisible(true);
      setTemplateName(`AFA${value}模板`);
      form.resetFields([
        'systemCode',
        'clstCode',
        'appCode'
      ]);
    }
    // 其实可以筛选集群
    // 但这里暂时不做此功能
  }

  /**
   * 交易所属系统栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const systemCodeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    form.resetFields([
      'clstCode',
      'appCode'
    ]);
    // 其实可以筛选集群
    // 但这里暂时不做此功能
    setSystemCode(value);
  }

  /**
   * 交易所属集群栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const clstCodeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    form.resetFields([
      'appCode'
    ]);
    // 根据全量的系统应用列表，所选的系统，集群，筛选应用列表
    const clstCode = value;
    const { appList } = props;
    if (appList && appList.length > 0) {
      const appData: DataItem[] = [];
      appList.forEach(item => {
        const srcSystemCode = item.systemCode;
        const srcClstCode = item.cluster;
        if (systemCode === srcSystemCode && clstCode === srcClstCode) {
          const dataItem: DataItem = {
            key: item.appCode,
            value: item.appName
          }
          appData.push(dataItem);
        }
      });
      setAppData(appData);
    }
  }

  /**
   * 点击下载导入模板文件
   */
  const importNameClick = () => {
    // console.log('importNameClick', afaVisible);
    // 下载文件
    const { downloadTemplateFile } = props;
    if (downloadTemplateFile) {
      const templateType = form.getFieldValue('templateType');
      if (afaVisible) {
        // 下载文件
        downloadTemplateFile(`afa${templateType}_trade_template.xls`);
      } else {
        downloadTemplateFile('trade_template.xlsx');
      }
    }
  }

  const { colon, modalTitle, modalWidth, modalVisible, systemData, clusterData, loading } = props;
  const formItemLayout = modalFormItemLayout;
  // 是否有表格勾选数据传进来，保证传进的值不为undefined
  // console.info(formData);
  // const templateName = afaVisible ? 'AFA模板' : '普通模板';
  const uploadTip = afaVisible ? '请上传AFA模板格式的文件，可通过AFA IDE导出场景流程清单，稍做修改即可上传' : '请上传普通模板格式的文件';
  const uploadProps: UploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: file => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
    maxCount: 1,
  };

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} form={form}>
        <Row>
          <Col span={12}>
            <FormItem label='模板类型' name='templateType' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '模板类型必输' }
              ]}
              initialValue={'1'}
            >
              <ASelect dataSource={templateTypeOptions} onChange={templateTypeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='导入模板下载' name='importName' {...formItemLayout} colon={colon}>
              <a title='点击下载模板并填写' onClick={() => importNameClick()}>{templateName}</a>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='上传文件' valuePropName='fileList' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '必须上传文件' },
              ]}
            >
              <Upload
                {...uploadProps}
              >
                <Button icon={<UploadOutlined />} title={uploadTip}>点击上传</Button>
              </Upload>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='交易负责人' name='owner' {...formItemLayout} colon={colon}
              rules={[
                { max: 20, message: '交易负责人最多允许输入20个字符' },
                { required: true, message: '交易负责人必输' }
              ]}
            >
              <Input placeholder='交易负责人账号，如luomi'/>
            </FormItem>
          </Col>
          {afaVisible && (
          <Col span={12}>
            <FormItem label='交易所属系统' name='systemCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属系统必输' }
              ]}
            >
              <ASelect dataSource={systemData} onChange={systemCodeChange}/>
            </FormItem>
          </Col>
          )}
        </Row>
        {afaVisible && (
        <Row>
          <Col span={12}>
            <FormItem label='交易所属集群' name='clstCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属集群必输' }
              ]}
            >
              <ASelect dataSource={clusterData} onChange={clstCodeChange}/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='交易所属应用' name='appCode' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '交易所属应用必输' }
              ]}
            >
              <ASelect dataSource={appData}/>
            </FormItem>
          </Col>
        </Row>)}
      </Form>
    </Modal>
  );
}

export default ImportTradeModal;